package com.fingard.dsp.bank.directbank.psbc11;

import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.directbank.psbc11.util.FileTransCmd;
import com.fingard.dsp.bank.directbank.psbc11.util.NcpaiFtpClient;
import com.fingard.dsp.bank.directbank.psbc11.util.SecurityHelper;
import com.fingard.dsp.bank.helpers.AskNumAmtHelper;
import com.fingard.dsp.bank.helpers.HelperResp;
import com.fingard.dsp.bank.helpers.SeqBatchInfo;
import com.fingard.dsp.bank.helpers.SeqBatchInfoHelper;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.generalobj.ExecResponse;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;

/**
 * 邮保通批量代收付
 * 
 * @author Cruise
 * @date 2018年09月28日
 */
public class PSBC11BatPayRec extends PSBC11Base implements IBatPayRec {
	/**
	 * 批量代付提交
	 */
	@Override
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		return d_BatPayRec(p_req1988);
	}

	/**
	 * 批量代付状态查询
	 */
	@Override
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
		return d_QryBatPayRec(p_req1998);
	}

	/**
	 * 批量代扣提交
	 */
	@Override
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		return d_BatPayRec(p_req9188);
	}

	/**
	 * 批量代扣状态查询
	 */
	@Override
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		return d_QryBatPayRec(p_req9198);
	}

	/**
	 * 批量代收付提交
	 * 
	 * @param p_reqBat
	 *            批量代收付请求对象
	 * @return 批量代收付响应对象
	 * @throws Exception
	 */
	public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
		retAts.reqSeqID = p_reqBat.reqBatchNO;

		boolean notifyGH = getBankConfig().getValueAsBool("notifyGH");

		NcpaiFtpClient ftpClient = null;
		SeqBatchInfoHelper seqBatHelper = null;
		AskNumAmtHelper askNumHelper = null;
		try {
			String trxCode = "";
			String businessFlag = "";
			if ("1988".equals(p_reqBat.reqHeader.transType) || "1988-ReSend".equals(p_reqBat.reqHeader.transType)) {
				trxCode = "PCK";
				businessFlag = "1";
			} else if ("9188".equals(p_reqBat.reqHeader.transType) || "9188-ReSend".equals(p_reqBat.reqHeader.transType)) {
				trxCode = "PKK";
				businessFlag = "0";
			}

			// 批次文件内容
			StringBuilder sbFileContent = new StringBuilder();

			// 明细序号及资金单笔支付流水号映射文件内容
			// StringBuilder sbSeqNoFileContent = new StringBuilder();
			seqBatHelper = new SeqBatchInfoHelper(p_reqBat.reqHeader.tenant, p_reqBat.getPayDateTime());
			SeqBatchInfo batInfo = null;
			if (p_reqBat.isReSend) {// 是重发代收付指令，批次号和流水号保持不变
				batInfo = seqBatHelper.loadFromDb(p_reqBat.reqHeader.bankCode, p_reqBat.reqBatchNO);// 返回不为空，则之前记录过
			}
			boolean existsBat = false;// 该批次在批次表中是否已经存在
			if (batInfo == null) {
				batInfo = new SeqBatchInfo();
				batInfo.loadFromReqBat(p_reqBat);
				int startBaseSeq = this.getBankConfig().getValueAsInt("fileStartBaseSeq", 0, "");
				batInfo.batSeqNo = seqBatHelper.getNextBatSeq(batInfo, startBaseSeq);
				if (batInfo.batSeqNo > 999) {
					retAts.respCode = "0";
					retAts.respInfo = "db内部批次序号已超过最大值(999)，实际值:["+batInfo.batSeqNo+"],无法发起交易!";
					retAts.transState = PaymentState.FAIL_Batch;
					retAts.payInfoCode = FailCode.E9999;
					retAts.writeRetToATS();
					return retAts;
				}
			} else {
				existsBat = true;
				// 校验一下总笔数总金额
				if (batInfo.totalAmt.compareTo(p_reqBat.getTotalAmt()) != 0 || batInfo.totalNum != p_reqBat.getTotalNum()) {
					retAts.respCode = "-1";
					retAts.respInfo = "重发的总笔数总金额校验不通过，原值（" + batInfo.totalNum + "，" + batInfo.totalAmt + "）现值（" + p_reqBat.totalNum + "，" + p_reqBat.totalAmt + "）";
					retAts.writeRetToATS();
					return retAts;
				}
			}
			String tmpPaySendDate = Format.Date8Format.format(p_reqBat.getPayDateTime());
			if (!"2".equals(batInfo.upFileState)) {// 文件未上传成功，再次上传
				// String batSeqNo = String.format("%3s",
				// getBatSeqNo(getTempFileDirectory())).replace(" ", "0");
				String batSeqNo = String.format("%3s", batInfo.batSeqNo).replace(" ", "0");
				// sbSeqNoFileContent.append(batSeqNo);

				askNumHelper = new AskNumAmtHelper(p_reqBat.reqHeader.tenant, p_reqBat.getPayDateTime());

				// 报文头信息：保险公司代码|送数据批次号|批存批扣标志(0-批扣,1-批存)|总笔数|总金额(带小数)|备用|备用|备用|备用|备用|备用|
				String tmpReqHeader = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|||||||", bankFront.corpNo, p_reqBat.reqBatchNO, businessFlag, p_reqBat.totalNum,
						p_reqBat.totalAmt);
				sbFileContent.append(tmpReqHeader);

				if (existsBat) {
					askNumHelper.initAskMappingOrder(p_reqBat.reqBatchNO);
				}
				// 每笔明细：序号:6|银行账号:20|金额:15|保险合同号:30|账户户名:30|批量交易类型:2|是否邮储客户:1|集团/股份标志:1|投保单号:30|费用记录号:20|备用:30|备用:30|备用:30|备用:30|备用:30|备用:30|
				int tmpSeqNo = 0;
				while (p_reqBat.readRecord()) {
					if (sbFileContent.length() > 0) {
						sbFileContent.append("\n");
					}
					// if (sbSeqNoFileContent.length() > 0) {
					// sbSeqNoFileContent.append("\n");
					// }

					String tmpSeqID = "";
					if (existsBat) {// 批次已经存在，本次属于重发，则根据askNumber取原批次的序号
						int orderno = askNumHelper.mappingOrder(p_reqBat.readedDetail.askNumber);
						if (orderno == -1) {
							retAts.respCode = "-1";
							retAts.respInfo = "在原批次中匹配不到重发的流水号" + p_reqBat.readedDetail.askNumber;
							retAts.writeRetToATS();
							return retAts;
						}
						tmpSeqID = String.valueOf(orderno);
					} else {
						tmpSeqNo++;
						askNumHelper.saveToLoaclDb(p_reqBat, p_reqBat.readedDetail, tmpSeqNo);
						tmpSeqID = String.valueOf(tmpSeqNo);
					}
					String batTransTypeFlag = p_reqBat.readedDetail.srcXElement.getSingleText(getBankConfig().getValueAsString("batTransType"));
					String batTransType = getBankConfig().getMapValueByKey("batTransTypeMapping", batTransTypeFlag);

					String oppAct = "";
					String oppName = "";
					if ("1988".equals(p_reqBat.reqHeader.transType) || "1988-ReSend".equals(p_reqBat.reqHeader.transType)) {
						oppAct = p_reqBat.readedDetail.recAct;
						oppName = p_reqBat.readedDetail.recName;
						if (StringHelper.isNullOrEmpty(batTransType)) {
							batTransType = "08";
						}
					} else if ("9188".equals(p_reqBat.reqHeader.transType) || "9188-ReSend".equals(p_reqBat.reqHeader.transType)) {
						oppAct = p_reqBat.readedDetail.payAct;
						oppName = p_reqBat.readedDetail.payName;
						if (StringHelper.isNullOrEmpty(batTransType)) {
							batTransType = "01";
						}
					}

					String payAmount = p_reqBat.readedDetail.payAmount;
					String contractNo = p_reqBat.readedDetail.srcXElement.getSingleText(getBankConfig().getValueAsString("contractNo"));

					String isNewCustomer = p_reqBat.readedDetail.srcXElement.getSingleText(getBankConfig().getValueAsString("isNewCustomer"));
					if (StringHelper.isNullOrEmpty(isNewCustomer)) {
						isNewCustomer = "Memo";
					}
					String psbcCustomerFlag = getBankConfig().getMapValueByKey("customerFlagMapping", isNewCustomer);
					if (StringHelper.isNullOrEmpty(psbcCustomerFlag)) {
						psbcCustomerFlag = "0";
					}

					String groupFlag = "N";
					String remark = p_reqBat.readedDetail.askNumber;

					String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}||||||", tmpSeqID, oppAct, payAmount, contractNo,
							oppName, batTransType, psbcCustomerFlag, groupFlag, "", "", remark);
					sbFileContent.append(tmpReqBodyDetail);

					// sbSeqNoFileContent.append(remark + "," + tmpSeqID);
				}
				WriteBankLogLn("批量代收付上传文件内容:\r\n" + sbFileContent.toString());

				// 生成待上传文件并写入内容
				// String tmpUploadFileName =
				batInfo.upFileName = bankFront.corpNo + trxCode + tmpPaySendDate + "9999" + batSeqNo + ".i";
				// String tmpLocalMarkPath
				batInfo.upFilePath = getTempFileDirectory() + File.separator + batInfo.upFileName;
				WriteBankLogLn2("本地批量代收付上传文件路径: " + batInfo.upFilePath);
				FileHelper.writeFile(batInfo.upFilePath, sbFileContent.toString(), getCharset());

				// 批次流水号映射存入本地
				// WriteBankLogLn2("本地批次流水映射文件内容:\r\n" + batSeqNo);
				// String tmpBatSeqNoPath =
				// getDataFileDirectory(p_reqBat.getPayDateTime()) +
				// File.separator + p_reqBat.reqBatchNO + ".txt";
				// WriteBankLogLn2("本地批次流水映射文件路径:" + tmpBatSeqNoPath);
				// FileHelper.writeFile(tmpBatSeqNoPath,
				// sbSeqNoFileContent.toString(), getCharset());
				// 保存批次
				if (!existsBat) {
					batInfo.upFileState = "5";
					try {
						seqBatHelper.insertSeqBatchInfo(batInfo);
					} catch (Exception ex) {
						this.WriteBankLogLn(ex);
						retAts.respInfo = "保存批次信息出现异常，不继续执行文件上传，异常信息：" + LogHelper.getStackTraceFirstLine(ex);
						if (!p_reqBat.isReSend) {
							retAts.respCode = "0";
							retAts.transState = PaymentState.FAIL_Batch;
							retAts.payInfoCode = "E9999";
						} else {
							retAts.respCode = "-1";
						}
						retAts.writeRetToATS();
						return retAts;
					}
				}

				if ("ftponly".equals(this.getBankConfig().getValueAsString("requestType").toLowerCase())) {
					FtpPortClient ftpPtClient = null;
					try {
						// 普通ftp
						FtpSet ftpSet = bankFront.getFtpSet("bat");
						ftpPtClient = new FtpPortClient(ftpSet);
						ExecResponse connResp = ftpPtClient.connect();
						if (!connResp.isSucceed) {
							retAts.respCode = "0";
							retAts.transState = PaymentState.FAIL_Batch;
							retAts.payInfoCode = "E9999";
							retAts.respInfo = connResp.getResultAsString();
							retAts.writeRetToATS();
							this.WriteBankLogLn(connResp.logMsg);
							return retAts;
						}

						FtpReceiver ftpReceiver = ftpPtClient.uploadFile(batInfo.upFilePath, batInfo.upFileName);
						if (ftpReceiver.isCompleted) {
							batInfo.upFileState = "2";
							seqBatHelper.updateUpFileState(batInfo);

							retAts.respCode = "0";
							retAts.respInfo = "上传ftp完成";
							retAts.transState = "00";
							retAts.payInfoCode = "00";
						} else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
							batInfo.upFileState = "3";
							seqBatHelper.updateUpFileState(batInfo);

							retAts.respCode = "0";
							retAts.transState = PaymentState.FAIL_Batch;
							retAts.payInfoCode = "E9999";
							retAts.respInfo = ftpReceiver.connMsg;
							retAts.writeRetToATS();
							return retAts;
						} else {

							retAts.respInfo = "上传至ftp发生异常：" + ftpReceiver.connMsg;
							if (!p_reqBat.isReSend) {
								retAts.respCode = "-1";
								retAts.transState = "";// PaymentState.FAIL_Batch;
								retAts.payInfoCode = "上传异常";
							} else {
								retAts.respCode = "-1";
							}
						}
					} catch (Exception ex) {
						retAts.respCode = "-1";
						retAts.respInfo = LogHelper.getStackTraceFirstLine(ex);
						WriteBankLogLn(ex);
						retAts.writeRetToATS();
						return retAts;
					} finally {
						if (ftpPtClient != null) {
							ftpPtClient.disconnect();
						}
					}
					WriteBankLogLn("notifyGH:" + notifyGH);
					if (notifyGH) {
						WriteBankLogLn("国华人寿个性化通知开始！");
						
						XmlTextWriter xmlWriter = new XmlTextWriter();
						xmlWriter.autoFormat = false;
						xmlWriter.writeStartElement("INFO");
						xmlWriter.writeElementString("TrCode", "816040");
						xmlWriter.writeElementString("CorpNo", bankFront.corpNo);
						xmlWriter.writeElementString("CorpType", "40");
						xmlWriter.writeElementString("TrDate", Format.Date8Format.format(p_reqBat.getPayDateTime()));
						xmlWriter.writeElementString("ReqSeqID", p_reqBat.reqBatchNO);
						xmlWriter.writeElementString("FileName", batInfo.upFileName);
						xmlWriter.writeElementString("TotalNum", p_reqBat.totalNum);
						xmlWriter.writeElementString("TotalAmt", p_reqBat.totalAmt);
						xmlWriter.writeElementString("SHA1Code", "");
						xmlWriter.writeEndDocument();
						
						WriteBankLogLn("国华人寿个性化通知内容："+xmlWriter.toXmlString());
						
						String p_reqStrLen = Integer.toString(xmlWriter.toXmlString().length());
						
						//String p_reqStr = "GHRS0" + p_reqStrLen + "816040" + xmlWriter.toXmlString() ;
						String p_reqStr = "GHRS0" + p_reqStrLen + "816040" + xmlWriter.toXmlString() ;

						String[] tmpStrRet = sendToBank(p_reqStr);

						if (tmpStrRet[0].length() == 0) {
							StringBuilder tmpSbMsg = new StringBuilder();
							XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
							if (tmpBkReader != null) {
								retAts.respCode = "0";
								String tmpRetCode = tmpBkReader.getFirstText("/INFO/RespCode");
								String tmpRetInfo = tmpBkReader.getFirstText("/INFO/RespMsg");
								if ("1".equals(tmpRetCode)) {
									retAts.respInfo = tmpRetInfo;
									retAts.transState = "4";
									retAts.payInfoCode = tmpRetCode;
									WriteBankLogLn("国华人寿个性化通知发送成功！");
								} else {
									retAts.respCode = "-1";
									retAts.respInfo = tmpRetInfo;
								}
							} else {
								retAts.respCode = "-1";
								retAts.respInfo = tmpSbMsg.toString();
							}
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = tmpStrRet[1];
						}

						retAts.writeRetToATS();
						return retAts;
					} else {
						retAts.writeRetToATS();
						return retAts;
					}
				} else if ("sharedir".equals(this.getBankConfig().getValueAsString("requestType").toLowerCase())) {
					// 共享目录
					String tmpFolder = "";
					if (StringHelper.hasAnyChar(bankFront.bkPayFolder)) {
						tmpFolder = StringHelper.trimEndFileSp(bankFront.bkPayFolder);
					} else {
						retAts.respCode = "0";
						retAts.transState = PaymentState.FAIL_Batch;
						retAts.payInfoCode = "E9999";
						retAts.respInfo = "bankFront未设置共享目录bkPayFolder";
						retAts.writeRetToATS();
						return retAts;
					}
					if (tmpFolder.toLowerCase().startsWith("smb://")) {
						String trgFilePath = tmpFolder + "/" + batInfo.upFileName;
						StringBuilder smbFileSb = new StringBuilder();
						int uploadRet = SmbFileUtil.smbWrite(trgFilePath, sbFileContent.toString(), getCharset(), smbFileSb);
						if (uploadRet < 0) {
							retAts.respCode = "-1";
							retAts.respInfo = smbFileSb.toString();
						} else {
							batInfo.upFileState = "2";
							seqBatHelper.updateUpFileState(batInfo);

							retAts.respCode = "0";
							retAts.respInfo = "写入smb共享目录完成";
							retAts.transState = "00";
							retAts.payInfoCode = "00";
						}
					} else {
						String shrFilePath = tmpFolder + File.separator + batInfo.upFileName;
						FileHelper.writeFile(shrFilePath, sbFileContent);
						batInfo.upFileState = "2";
						seqBatHelper.updateUpFileState(batInfo);

						retAts.respCode = "0";
						retAts.respInfo = "写入共享目录完成";
						retAts.transState = "00";
						retAts.payInfoCode = "00";
					}
					retAts.writeRetToATS();
					return retAts;
				}

				// 上传批次文件
				ftpClient = new NcpaiFtpClient();
				FileTransCmd tmpFileCommand = new FileTransCmd();
				tmpFileCommand.setVs_outsys_code("9940001"); /* 请求接收系统代码，固定 */
				tmpFileCommand.setVs_req_flag("0"); /* 请求标志，固定 */
				tmpFileCommand.setVs_send_recv_flag("0"); /* 向保险系统发送文件标志,固定 */
				tmpFileCommand.setVs_local_file_dir("insu/" + bankFront.corpNo); /*
																				 * 保险系统文件保存目录
																				 * ,
																				 * insu固定
																				 * ，
																				 * 0001
																				 * 为各保险公司代码
																				 */
				tmpFileCommand.setVs_local_file_name(batInfo.upFileName); /* 保险系统接受文件名 */
				tmpFileCommand.setVs_remote_file_dir(getTempFileDirectory() + File.separator); /*
																								 * 上传文件本地路径
																								 * ，
																								 * 完全路径
																								 */
				tmpFileCommand.setVs_remote_file_name(batInfo.upFileName); /* 上传文件名 */

				try {
					ftpClient.createSocketClient(ftpClient.ipAddress, ftpClient.port);
				} catch (Exception ex) {
					WriteBankLogLn(ex);
					retAts.respInfo = "连接ftp服务器失败：" + LogHelper.getStackTraceFirstLine(ex);
					if (!p_reqBat.isReSend) {
						retAts.respCode = "0";
						retAts.transState = PaymentState.FAIL_Batch;
						retAts.payInfoCode = "E9999";
					} else {
						retAts.respCode = "-1";
					}

					retAts.writeRetToATS();
					return retAts;
				}

				boolean isSended = ftpClient.sendFileToHost(ftpClient.clientSocket, tmpFileCommand);
				if (isSended) {
					WriteBankLogLn("上传至邮储系统--完成");
					batInfo.upFileState = "2";
					int rowAff = seqBatHelper.updateUpFileState(batInfo);
					if (rowAff != 1 && !p_reqBat.isReSend) {
						retAts.respCode = "0";
						retAts.respInfo = "更新批次" + batInfo.reqBatchNo + "的上传状态失败，影响行数：" + rowAff;
						retAts.transState = PaymentState.FAIL_Batch;
						retAts.payInfoCode = "上传状态更新失败";
						retAts.writeRetToATS();
						return retAts;
					}

					boolean isUpDotF = this.getBankConfig().getValueAsBool("upFinishedFile.f");
					if (isUpDotF) {
						String upFileDotF = batInfo.upFilePath + ".f";
						FileHelper.writeFile(upFileDotF, "", getCharset());
						WriteBankLogLn("上传.f文件：" + upFileDotF);
						tmpFileCommand.setVs_local_file_name(batInfo.upFileName + ".f"); /* 保险系统接受文件名 */
						tmpFileCommand.setVs_remote_file_dir(getTempFileDirectory() + File.separator); /*
																										 * 上传文件本地路径
																										 * ，
																										 * 完全路径
																										 */
						tmpFileCommand.setVs_remote_file_name(batInfo.upFileName + ".f"); /* 上传文件名 */
						boolean isSendDotF = ftpClient.sendFileToHost(ftpClient.clientSocket, tmpFileCommand);
						if (isSendDotF) {
							WriteBankLogLn("上传.f文件完成");
						} else {
							WriteBankLogLn("上传.f文件--失败");
							retAts.respInfo = "上传.f文件--失败";
							if (!p_reqBat.isReSend) {
								retAts.respCode = "-1";
								// retAts.transState = PaymentState.FAIL_Batch;
								retAts.payInfoCode = "上传.f文件失败";
							} else {
								retAts.respCode = "-1";
							}
							retAts.writeRetToATS();
							return retAts;
						}
					}

					float realSleepTime = getBankConfig().getValueAsFloat("submitBatWaitTime");
					Thread.sleep((long) (realSleepTime * 1000));
				} else {
					WriteBankLogLn("上传至邮储系统--失败");
					retAts.respInfo = "上传至邮储系统--失败";
					if (!p_reqBat.isReSend) {
						retAts.respCode = "0";
						retAts.transState = PaymentState.FAIL_Batch;
						retAts.payInfoCode = "上传失败";
					} else {
						retAts.respCode = "-1";
					}
					retAts.writeRetToATS();
					return retAts;
				}
			} else {
				WriteBankLogLn("批量代收付文件之前已经上传成功，本次重发不再上传");
			}

			// 发送通知
				String tmpNotifyMsg = "816040|" + bankFront.corpNo + "|40|" + tmpPaySendDate + "|" + p_reqBat.reqBatchNO + "|" + batInfo.upFileName + "|"
						+ p_reqBat.totalNum + "|" + p_reqBat.totalAmt + "|" + SecurityHelper.generateMackey(batInfo.upFilePath) + "|";
				String tmpNotifyMsgLen = String.format("%6s", tmpNotifyMsg.getBytes(getCharset()).length).replace(" ", "0");
				tmpNotifyMsg = "POST816040" + tmpNotifyMsgLen + tmpNotifyMsg;
				String[] tmpStrRet = sendToBank(tmpNotifyMsg);

				if (tmpStrRet[0].length() == 0) {
					// StringBuilder tmpStr = new StringBuilder();
					String[] Str = tmpStrRet[1].split("\\|");
					// for (int i = 0; i < Str.length; i++) {
					// tmpStr.append(Str[i]);
					// }
					if (Str.length > 10) {
						String tmpRetCode = Str[9];
						String tmpRetMsg = Str[10];
						retAts.respInfo = tmpRetMsg;
						if (Str[4].equals(p_reqBat.reqBatchNO)) {
							retAts.respCode = "0";
							retAts.reqSeqID = p_reqBat.reqBatchNO;
							if (Str[5].equals(batInfo.upFileName)) {
								retAts.transState = tmpRetCode;
								retAts.payInfoCode = tmpRetMsg;
							} else {
								retAts.respCode = "-1";
								retAts.respCode = "校验码：" + Str[5] + "校验失败";
							}
						} else {
							retAts.respCode = "-1";
							retAts.respCode = "响应批次号：" + Str[4] + "校验失败";
						}
					} else {
						retAts.respCode = "-1";
						retAts.respCode = "未能识别响应报文格式";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpStrRet[1];
				}
			
		} catch (Exception ex) {
			retAts.respCode = "-1";
			retAts.respInfo = LogHelper.getStackTraceFirstLine(ex);
			WriteBankLogLn(ex);
		} finally {
			if (seqBatHelper != null) {
				seqBatHelper.close();
			}
			if (askNumHelper != null) {
				askNumHelper.close();
			}
			if (ftpClient != null) {
				ftpClient.closeSocketClient(ftpClient.clientSocket);
			}
		}

		retAts.writeRetToATS();
		return retAts;
	}

	/**
	 * 批量代收付状态查询
	 * 
	 * @param p_reqQryBat
	 * @return
	 * @throws Exception
	 */
	public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
		retAts.reqSeqID = p_reqQryBat.reqBatchNO;
		SeqBatchInfoHelper seqBatHelper = null;
		AskNumAmtHelper askNumHelper = null;
		try {
			String trxCode = "";
			if ("1998".equals(p_reqQryBat.reqHeader.transType)) {
				trxCode = "PCK";
			} else if ("9198".equals(p_reqQryBat.reqHeader.transType)) {
				trxCode = "PKK";
			}
			seqBatHelper = new SeqBatchInfoHelper(p_reqQryBat.reqHeader.tenant, p_reqQryBat.getBgnDateTime());
			// String tmpBatSeqNoPath =
			// getDataFileDirectory(p_reqQryBat.getBgnDateTime()) +
			// File.separator + p_reqQryBat.reqBatchNO + ".txt";
			// WriteBankLogLn2("本地批次流水映射文件路径:" + tmpBatSeqNoPath);
			// String tmpSeqNOMappingContent =
			// FileHelper.readFileText(tmpBatSeqNoPath, getCharset());
			// String tmpBatSeqNo = tmpSeqNOMappingContent.split("\n")[0];
			// String[] tmpSeqNoArray =
			// tmpSeqNOMappingContent.substring(tmpSeqNOMappingContent.indexOf("\n")+1).split("\n");
			SeqBatchInfo batInfo = seqBatHelper.loadFromDb(p_reqQryBat.reqHeader.bankCode, p_reqQryBat.reqBatchNO);
			if (batInfo == null) {
				retAts.respCode = "-1";
				retAts.respInfo = "查不到该批次的提交记录，请在未知状态下重发代收付指令";
				retAts.writeAfterDetail();
				return retAts;
			}
			String tmpBatSeqNo = String.format("%3s", batInfo.batSeqNo).replace(" ", "0");

			String tmpResultFileName = bankFront.corpNo + trxCode + Format.Date8Format.format(p_reqQryBat.getBgnDateTime()) + "9999" + tmpBatSeqNo + ".o";
			String tmpResultFilePath = getTempFileDirectory(p_reqQryBat.getBgnDateTime()) + File.separator + tmpResultFileName;
			WriteBankLogLn2("批次结果文件保存本机路径:" + tmpResultFilePath);

			if (!FileHelper.existFile(tmpResultFilePath)) {
			    String requestType = "";
			    boolean useDownRequestType = getBankConfig().getValueAsBool("useDownRequestType");
			    WriteBankLogLn("下载是否使用单独的交互方式(useDownRequestType):" + useDownRequestType);
			    if (useDownRequestType) {
                    requestType = getBankConfig().getValueAsString("requestTypeDownload").toLowerCase();
                } else {
                    requestType = getBankConfig().getValueAsString("requestType").toLowerCase();
                }
				if ("ftponly".equals(requestType)) {
					FtpPortClient ftpPtClient = null;
					try {
						// 普通ftp
						FtpSet ftpSet = bankFront.getFtpSet("bat");
						ftpPtClient = new FtpPortClient(ftpSet);
						ExecResponse connResp = ftpPtClient.connect();
						if (!connResp.isSucceed) {
							retAts.respCode = "-1";
							retAts.respInfo = connResp.getResultAsString();
							this.WriteBankLogLn(connResp.logMsg);
							retAts.writeAfterDetail();
							return retAts;
						}
						String tmpDownTmpPath = getTempFileDirectory() + File.separator + tmpBatSeqNo + "." + this.getQryTransID() + ".tmp.o";
						FtpReceiver ftpReceiver = ftpPtClient.downloadFile(tmpResultFileName, tmpDownTmpPath);
						if (ftpReceiver.isCompleted) {
							FileHelper.moveFile(new File(tmpDownTmpPath), new File(tmpResultFilePath));
						} else {
							FileHelper.deleteFileIfExists(tmpDownTmpPath);
							retAts.respCode = "-1";
							retAts.respInfo = "从ftp下载出现异常：" + ftpReceiver.connMsg;
							retAts.writeAfterDetail();
							return retAts;
						}
					} catch (Exception ex) {
						retAts.respCode = "-1";
						retAts.respInfo = LogHelper.getStackTraceFirstLine(ex);
						WriteBankLogLn(ex);
						retAts.writeAfterDetail();
						return retAts;
					} finally {
						if (ftpPtClient != null) {
							ftpPtClient.disconnect();
						}
					}
				} else if ("sharedir".equals(requestType)) {
					// 共享目录
					String tmpFolder = "";
					if (StringHelper.hasAnyChar(bankFront.bkQryPayFolder)) {
						tmpFolder = StringHelper.trimEndFileSp(bankFront.bkQryPayFolder);
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "bankFront未设置共享目录bkQryPayFolder";
						retAts.writeAfterDetail();
						return retAts;
					}
					if (tmpFolder.toLowerCase().startsWith("smb://")) {

						StringBuilder smbFileSb = new StringBuilder();
						int downRet = SmbFileUtil.smbDownload(getTempFileDirectory(), tmpFolder, tmpResultFileName, smbFileSb);
						if (downRet > 0) {
							this.WriteBankLogLn("从smb共享目录下载成功");
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = smbFileSb.toString();
							retAts.writeAfterDetail();
							return retAts;
						}
					} else {
						String shrFilePath = tmpFolder + File.separator + tmpResultFileName;
						FileHelper.copyFile(new File(shrFilePath), new File(tmpResultFilePath));
						this.WriteBankLogLn("从共享目录复制成功");
					}
				}
			}
			File tmpResultFile = new File(tmpResultFilePath);
			if (tmpResultFile.exists()) {
				if (!"2".equals(batInfo.downFileState)) {
					batInfo.downFilePath = tmpResultFilePath;
					batInfo.downFileState = "2";
					seqBatHelper.updateUpFileState(batInfo);
				}
				String tmpStrRet = FileHelper.readFileText(tmpResultFilePath, getCharset());
				WriteBankLogStep3(tmpStrRet);
				askNumHelper = new AskNumAmtHelper(p_reqQryBat.reqHeader.tenant, p_reqQryBat.getBgnDateTime());
				askNumHelper.matchActByStartWith = true;
				askNumHelper.initMatch(p_reqQryBat.reqBatchNO);
				retAts.respCode = "0";
				retAts.reqSeqID = p_reqQryBat.reqBatchNO;

				StringReader strReader = new StringReader(tmpStrRet);
				BufferedReader tmpReader = new BufferedReader(strReader);
				tmpReader.readLine();

				int rdCounting = 0;
				int matchedCount = 0;
				while (true) {
					String eachline = tmpReader.readLine();
					if (eachline == null) {
						break;
					}
					if (eachline.indexOf("|") > 0) {
						rdCounting++;
						String[] bodyValues = eachline.split("\\|");

						RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

						if (p_reqQryBat.reqHeader.transType.equals("1998")) {
							tmpRetDetail.recAct = bodyValues[2];
							tmpRetDetail.recName = bodyValues[5];
						} else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
							tmpRetDetail.payAct = bodyValues[2];
							tmpRetDetail.payName = bodyValues[5];
						}

						tmpRetDetail.payAmount = bodyValues[3];
						tmpRetDetail.result = bodyValues[1];

						String bkRetCode = bodyValues[1].trim();
						String bkRetInfo = bodyValues[10].trim();
						String setRayInfoCode = "";
						String setMemo = "";
						if (bkRetInfo.indexOf("-") > 0){
							String[] tmpSpStr = bkRetInfo.split("-");
							setRayInfoCode = tmpSpStr[0];
							setMemo = tmpSpStr[1];
						}
						if(StringHelper.isNullOrEmpty(setRayInfoCode)){
							setRayInfoCode = bkRetCode;
						}
						if(StringHelper.isNullOrEmpty(setMemo)){
							setMemo = bkRetInfo;
						}
						if ("ZZ".equals(setRayInfoCode.toUpperCase())){
							setRayInfoCode = bkRetInfo;
						}
						boolean setByInfoIfZZ = this.getBankConfig().getValueAsBool("setByInfoIfZZ");
						if (setByInfoIfZZ){//只有ZZ时，提取信息里的值//102003-可用余额不足
							if ("ZZ".equals(bkRetCode.toUpperCase()) && bkRetInfo.indexOf("-") > 0){
								tmpRetDetail.payInfoCode = setRayInfoCode;
							}else if ("ZZ".equals(bkRetCode.toUpperCase())){
								tmpRetDetail.payInfoCode = bkRetInfo;
							}else{
								tmpRetDetail.payInfoCode = bkRetCode;
							}
							tmpRetDetail.memo = bkRetInfo;
						}else{
							tmpRetDetail.payInfoCode = setRayInfoCode;
							tmpRetDetail.memo = setMemo;
						}
						int orderno = Integer.parseInt(bodyValues[0]);

						try {
							if (askNumHelper.matchAskNum(p_reqQryBat.reqHeader.transType, tmpRetDetail, orderno, false)) {
								matchedCount++;
								retAts.writeRetDetail(tmpRetDetail);
							}
						} catch (Exception ex) {
							WriteBankLogLn(ex);
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "银行返回明细数据格式非法!";
					}
				}
				HelperResp resp = askNumHelper.checkMatchCount(rdCounting, matchedCount);
				if (!resp.isCompleted) {// 总笔数校验不通过
					retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
					retAts.reqSeqID = p_reqQryBat.reqBatchNO;
					retAts.respCode = "-1";
					retAts.respInfo = resp.sbMsg.toString();
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "暂无结果文件!";
			}
		} catch (Exception ex) {
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		} finally {
			if (seqBatHelper != null) {
				seqBatHelper.close();
			}
			if (askNumHelper != null) {
				askNumHelper.close();
			}
		}

		retAts.writeAfterDetail();
		return retAts;
	}
}